<template>
  <el-row :gutter="15">
    <el-col :span="12">
      <el-card>
        <div slot="header" class="clearfix">
          <span>角色信息</span>
        </div>
        <el-row>
          <el-form :model="model" label-width="100px" ref="elForm">
            <el-form-item v-if="isEdit && !editing" label="角色名称" prop="name">
              <span>{{ model.name }}</span>
            </el-form-item>
            <el-form-item v-else label="角色名称" prop="name" :rules="[
            {required: true, message: '角色名称必须', trigger: 'blur'}
          ]">
              <el-input v-model="model.name"></el-input>
            </el-form-item>
          </el-form>
        </el-row>
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card>
        <div slot="header" class="clearfix">
          <span>菜单权限</span>
        </div>
        <el-tree
          :key="editing"
          :props="{label: 'text'}"
          :default-checked-keys="checkedMenuIds"
          :show-checkbox="editing" :data="treeData"
          node-key="value"
          ref="elTree">
        </el-tree>
      </el-card>
    </el-col>
    <el-col :span="24">
      <el-card>
        <el-row v-if="!isEdit">
          <el-col :span="8" :offset="8">
            <el-button class="btn-block" type="primary" :loading="createLoading" @click.prevent="httpCreatePost">添加</el-button>
          </el-col>
        </el-row>
        <el-row v-if="isEdit">
         <template v-if="!editing">
           <el-col :span="24" class="text-center">
             <el-button class="btn-block" type="primary" @click.prevent="toEditing">修改</el-button>
             <el-button class="btn-block" type="danger" :loading="createLoading" @click.prevent="deleteRole">
               <i class="fa fa-trash"></i>删除
             </el-button>
           </el-col>
         </template>
         <template v-if="editing">
           <el-col :span="24" class="text-center">
             <el-button class="btn-block" type="primary" :loading="createLoading" @click.prevent="httpCreatePost">保存</el-button>
             <el-button class="btn-block" type="danger" :loading="createLoading" @click.prevent="cancel">取消修改</el-button>
           </el-col>
         </template>
        </el-row>
      </el-card>
    </el-col>
    <!--<el-col :span="24">-->
      <!--{{ checkedMenuIds }}-->
    <!--</el-col>-->
  </el-row>
</template>
<script>
import {dotData, arrayToTree, copy, confirm, alert, hasChildCallBack} from '@/utils'
// import L from 'lodash'
export default {
  name: 'roleShow',
  data() {
    return {
      id: this.$route.params.id,
      roleDetail: [],
      menuData: [],
      model: {
        name: ''
      },
      hasCheckBox: false,
      createLoading: false,
      saveLoading: false,
      editing: false,
      projectType: 'storeWeb',
      roleMenuList: [],
      allMenuList: [],
      checkeMenuIds: []
    }
  },
  created() {
    if (this.isEdit) { // 详情
      this.httpGetRoleDetail()
    } else { // 新增、修改
      this.editing = true
      this.httpGetAllMenu()
    }
  },
  computed: {
    isEdit() {
      return !!this.id
    },
    // 动态计算并重组数据
    treeData() {
      const data = this.editing ? this.allMenuList : this.roleMenuList
      if (Array.isArray(data)) {
        return arrayToTree(data, 'id', 'parentId', 'children', 0, true)
      }
      return []
    },
    // 修改之前 默认已被选中的菜单Id
    checkedMenuIds() {
      if (this.editing && Array.isArray(this.roleMenuList)) {
        let temp = []
        hasChildCallBack(arrayToTree(this.roleMenuList, 'id', 'parentId', 'children', 0, true), (v) => {
          temp.push(v.id)
        }, 'children') // 被选中的id
        // 过滤出 不含 半选的父节点 的子节点id
        // console.log('111111', this.roleMenuList)
        // console.log('22222', this.roleMenuList.filter(v => temp.indexOf(v.value) < 0).map(v => v.value))
        return this.roleMenuList.filter(v => temp.indexOf(v.value) < 0).map(v => v.value)
      }
      return []
    }
  },
  methods: {
    // 获取所有菜单 httpGetResponse
    httpGetAllMenu() {
      return this.$ajax.get('/ms-common-user/menu/menu-list', {projectType: this.projectType}).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          if (Array.isArray(response.data)) {
            this.allMenuList = response.data.map(v => {
              v.value = v.id
              v.text = v.name
              return v
            })
          }
        }
      })
    },
    // 获取当前角色名和 其对应的菜单数据
    httpGetRoleDetail() { // httpGetResponse
      this.$ajax.get('/ms-common-user/role/getMenuByRoleId', {roleId: this.id}).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          const data = dotData(response, 'data')
          this.model.name = dotData(data, 'name') // 角色名
          console.log(data)
          if (Array.isArray(data.menuList)) {
            this.roleMenuList = data.menuList.map(v => {
              v.value = v.id
              v.text = v.name
              return v
            })
          }
        }
      })
    },
    // 新增
    httpCreatePost() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          return
        }
        let data = copy(this.model, true)
        // 获取被选中的节点对象(含半选的父节点，后端要要)
        const nodes = this.$refs.elTree.getCheckedNodes(false, true)
        data.ids = []
        // 从中取出id
        if (Array.isArray(nodes)) {
          data.ids = nodes.map(v => v.value)
        }
        console.log(data.ids)
        if (data.ids.length <= 0) {
          alert('请选择菜单权限')
          return
        }
        this.createLoading = true
        data.project = this.projectType
        if (this.id) {
          data.id = this.id
        }
        this.$ajax.post('/ms-common-user/role/add-role', data).then(response => {
          const success = dotData(response, 'success')
          if (success) {
            confirm('操作成功', undefined, {type: 'success'}).then(_ => {
              this.toIndex()
            })
          }
          this.createLoading = false
        }).catch(_ => {
          this.createLoading = false
        })
      })
    },
    // toIndex
    toIndex() {
      this.$router.push({path: '/ss-oms/information/role'})
    },
    // 编辑状态
    toEditing() {
      this.editing = true // 编辑
      // 获取所有的菜单
      this.httpGetAllMenu()
    },
    // 删除角色
    deleteRole() {
      confirm('删除后关联帐号的权限也将被删除!', '是否确认删除该角色？', {
        confirmButtonLoading: true,
        type: 'waring',
        confirmCallBack: ({close, confirmButtonLoadingClose}) => {
          this.$ajax.post('/ms-common-user/role/delete-role', {id: this.id, project: this.projectType}).then(response => {
            confirmButtonLoadingClose()
            const success = dotData(response, 'success')
            if (success) {
              close().then(_ => {
                confirm('删除成功', undefined, {type: 'success'}).then(_ => {
                  this.toIndex()
                })
              })
            }
          }).catch(_ => {
            confirmButtonLoadingClose()
          })
        }
      })
    },
    // 取消修改
    cancel() {
      this.editing = false
    }
  }
}
</script>
